package com.ficus.road.maintain.service.third;

import com.ficus.road.maintain.core.exception.BadRequestException;
import com.ficus.road.maintain.core.model.*;
import com.ficus.road.maintain.core.model.oss.AliyunOssResult;
import com.ficus.road.maintain.core.model.third.DiankeCreateHitRequest;
import com.ficus.road.maintain.core.model.third.DiankeDichargeHitRequest;
import com.ficus.road.maintain.ditalTwin.dao.DigitalHitDao;
import com.ficus.road.maintain.util.AliyunOSSUtil;
import com.ficus.road.maintain.util.ImageUtil;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class DiankeService {

    private final DigitalHitDao hitDao;
    private final AliyunOSSUtil aliyunOSSUtil;

    public String createHit(DiankeCreateHitRequest request) {
        Hit one = hitDao.findOne(new Query(Criteria.where("attrs.disease_uid").is(request.getId())));
        if (Objects.nonNull(one)) {
            throw new BadRequestException("hit already exist");
        }
        Hit hit = new Hit();
        HitAttrs attrs = new HitAttrs();
        attrs.setRoadName(request.getRoadName());
        attrs.setConfirmation(Confirmation.builder().status(Confirmation.ConfirmationStatus.CORRECT).build());
        attrs.setSectionCode(request.getSectionCode());
        attrs.setLocation(Lists.newArrayList(request.getLgt(),request.getLat()));
        attrs.setGpsLocation(GpsLocation.builder().latitude(request.getLat()).longitude(request.getLgt()).build());
        attrs.setDescriptionThird(request.getDescription());
        attrs.setDiseaseUid(request.getId());
        attrs.setTraCongestionIndex(request.getTraCongestionIndex());

        if (!StringUtils.isEmpty(request.getImageUrl())) {
            attrs.setSceneImage(request.getImageUrl());
        } else if (!StringUtils.isEmpty(request.getImageBase64())) {
            AliyunOssResult ossResult = aliyunOSSUtil.uploadImg(UuidUtil.getTimeBasedUuid() + ".jpg",
                    ImageUtil.base64ToBytes(request.getImageBase64()));
            if (ossResult.getCode() == 200) {
                attrs.setSceneImage(ossResult.getUrl());
                attrs.setSceneImageName(ossResult.getName());
            }

        }
        attrs.setStatus(HitStatusEnum.NEW);
        hit.setAttrs(attrs);
        hit.setHitTime(request.getHitTime());
        hit.setFirstHitTime(request.getHitTime());
        hit.setType(request.getType());
        hit.setCreationTime(request.getHitTime());
        if (CollectionUtils.isEmpty(request.getSubjects())) {
            hit.setSubjects(Lists.newArrayList());
        } else {
            List<HitSubject> subjects = request.getSubjects().stream().map(t -> {
                HitSubject subject = new HitSubject();
                subject.setBbox(t);
                subject.setRelBbox(RelBbox.builder()
                        .h(Double.valueOf(t.getH()))
                        .w(Double.valueOf(t.getW()))
                        .y(Double.valueOf(t.getY()))
                        .x(Double.valueOf(t.getX()))
                        .build());
                return subject;
            }).collect(Collectors.toList());
            hit.setSubjects(subjects);
        }
        hit.setLastModificationTime(System.currentTimeMillis() / 1000);
        hit.setList(Lists.newArrayList(HistoryHit.fromHit(hit)));
        Hit insert = hitDao.insert(hit);
        return insert.getId();
    }

    public String discharge(DiankeDichargeHitRequest request, String thirdHitId) {
        Hit one = hitDao.findOne(new Query(Criteria.where("attrs.disease_uid").is(thirdHitId)));
        if (Objects.isNull(one)) {
            throw new BadRequestException("hit is empty");
        }
        HitAttrs attrs = one.getAttrs();
        if (!StringUtils.isEmpty(request.getImageUrl())) {
            attrs.setResolveImageUrl(Lists.newArrayList(request.getImageUrl()));
        } else if (!StringUtils.isEmpty(request.getImageBase64())) {
            AliyunOssResult ossResult = aliyunOSSUtil.uploadImg(UuidUtil.getTimeBasedUuid() + ".jpg",
                    ImageUtil.base64ToBytes(request.getImageBase64()));
            if (ossResult.getCode() == 200) {
                attrs.setResolveImageUrl(Lists.newArrayList(ossResult.getUrl()));
            }
        }
        HistoryHit historyHitConfirmed = new HistoryHit();
        historyHitConfirmed.setHitTime(System.currentTimeMillis()/1000);
        HistoryHitAttrs historyHitAttrs = new HistoryHitAttrs();
        historyHitAttrs.setStatus(HitStatusEnum.CONFIRMED);
        historyHitAttrs.setDiseaseUid(one.getAttrs().getDiseaseUid());
        historyHitAttrs.setSceneImage(attrs.getResolveImageUrl().get(0));
        historyHitConfirmed.setAttrs(historyHitAttrs);
        one.getList().add(historyHitConfirmed);

        HistoryHit historyHitComplete = new HistoryHit();
        historyHitComplete.setHitTime(System.currentTimeMillis()/1000);
        HistoryHitAttrs historyHitAttrs1 = new HistoryHitAttrs();
        historyHitAttrs1.setStatus(HitStatusEnum.COMPLETE);
        historyHitAttrs1.setDescription("现场已处置");
        historyHitAttrs1.setDiseaseUid(one.getAttrs().getDiseaseUid());
        historyHitAttrs1.setSceneImage(attrs.getResolveImageUrl().get(0));
        historyHitConfirmed.setAttrs(historyHitAttrs);
        one.getList().add(historyHitConfirmed);

        attrs.setStatus(HitStatusEnum.CONFIRMED);
        attrs.setDescription(request.getDescription());
        one.setAttrs(attrs);
        one.setLastModificationTime(System.currentTimeMillis() / 1000);
        hitDao.saveOrUpdate(one);
        return one.getId();
    }
}
